797. 所有可能的路径
为保证权益,题目请参考 797. 所有可能的路径(From LeetCode).
解决方案1
Python
python
# 797. 所有可能的路径
# https://leetcode-cn.com/problems/all-paths-from-source-to-target/
from typing import List
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
self.ans = []
self.visited = [False] * len(graph)
self.visited[0] = True
self.tmpPath = [0]
def dfs(i):
if i == len(graph)-1:
self.ans.append(self.tmpPath.copy())
return
for target in graph[i]:
if self.visited[target] == False:
self.visited[target] = True
self.tmpPath.append(target)
dfs(target)
self.tmpPath.pop()
self.visited[target] = False
dfs(0)
return self.ans
if __name__ == "__main__":
solution = Solution()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27